<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="系统名称" prop="tenantname" label-width="100px">
        <el-input v-model="queryParams.tenantname" placeholder="请输入系统名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:role:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:role:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:role:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="roleList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" prop="entName" align="center" width="200" />
      <el-table-column label="监测站名称" align="center" prop="stationName" width="150">
        <template #default="scope">
          <span>{{ scope.row.stationName || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在地区" prop="stationAddress" :show-overflow-tooltip="false" align="center" width="100" />
      <el-table-column label="经纬度" prop="lngLat" :show-overflow-tooltip="false" align="center" width="100" />
      <el-table-column label="监测站类型" align="center" prop="stationName" width="150">
        <template #default="scope">
          <!-- 使用对象替代 Map -->
          <span>{{ stationTypeMap[scope.row.showType] || '未知类型' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="母线数量" align="center" prop="alarmCount" width="80"></el-table-column>
      <el-table-column label="支线数量" align="center" prop="branchCount" width="80"></el-table-column>
      <el-table-column label="设备数量" align="center" prop="deviceCount" width="80"></el-table-column>
      <el-table-column label="所有监测点" align="center" prop="senserCount" width="120"></el-table-column>


      <el-table-column fixed="right" label="操作" align="center" min-width="260px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleTonav(scope.row)">总览</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.curPage"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="系统" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入系统" />
        </el-form-item>
        <el-form-item label="系统链接地址" prop="tenantDoMain">
          <el-input v-model="form.tenantDoMain" placeholder="请输入系统链接地址" />
        </el-form-item>
        <el-form-item label="系统详细介绍" :required="false" prop="tenantDes">
          <el-input v-model="form.tenantDes" type="textarea" placeholder="请输入系统详细介绍"></el-input>
        </el-form-item>
        <el-form-item label="添加系统排序" :required="false" prop="tenantOrders">
          <el-input-number v-model="form.tenantOrders" controls-position="right" :min="0" :max="9" change="handleChange"
            @blur="handleChange" />
        </el-form-item>
        <!-- 新增经纬度字段 -->
        <el-form-item label="经纬度" prop="lngLat">
          <el-input v-model="form.lngLat" placeholder="经度,纬度" style="width: 220px" readonly />
          <el-button type="primary" @click="openMapPicker" style="margin-left: 10px">选择位置</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <AMapPointPickerInDialog ref="mapPickerDialogRef" @confirm="handleConfirm" />
    <!-- <MessagePopup ref="messagePopupRef" :show="hasNewMessage" @close="hasNewMessage = false" /> -->
  </div>
</template>

<script setup name="Role">
import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'
import { useWebSocket } from '@/utils/useWebSocket.js'; //引入自定义的 WebSocket 钩子函数
import MessagePopup from '@/components/MessagePopup';//消息弹窗
import AMapPointPickerInDialog from '@/components/Amap/AMapPointPickerInDialog.vue';

const userInfo = useInfoStore();
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");
const router = useRouter();
const { proxy } = getCurrentInstance();
const mapPickerDialogRef = ref(null); //地图示例

// // 配置 WebSocket 连接地址（需替换为实际地址）
// const wsUrl = 'ws://www.icloudsafety.com/dianli/stationMonitorWs/100219';
// // 初始化 WebSocket 实例
// const {
//   isConnected,
//   hasNewMessage,
//   sendMessage,
//   on,
//   destroy,
//   initWebSocket
// } = useWebSocket(wsUrl, {
//   reconnectTimes: 3, // 自定义重连次数
//   heartbeatInterval: 15000 // 自定义心跳间隔
// });
// const messagePopupRef = ref(null);

// // 订阅自定义消息事件
// on('onMessage', (msg) => {
//   if (messagePopupRef.value) {
//     const mockEvent = { data: msg };
//     messagePopupRef.value.handleMessage(mockEvent);
//   }
// });

// // 组件挂载时初始化连接
// onMounted(() => {
//   initWebSocket();
// });

// // 组件卸载时销毁连接
// onBeforeUnmount(() => {
//   destroy();
// });

const roleList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const stationTypeMap = {
  1: '线路站',
  2: '列表站',
  3: '实验站',
};
const data = reactive({
  form: {
    tenantName: null,
    tenantDoMain: null,
    tenantDes: null,
    tenantOrders: 0,
    id: null
  },
  queryParams: {
    curPage : 1,
    pageSize: 10,
  },
  rules: {
    tenantName: [{ required: true, message: "系统名称不能为空", trigger: "blur" }],
    tenantDoMain: [{ required: true, message: "系统链接地址为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 地图选点信息
function handleConfirm(point) {
 
}

/** 查询角色列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.stationlist(queryParams.value).then(response => {
    roleList.value = response.data.records;
    total.value = response.data.total || 0;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.curPage = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除系统"' + row.tenantName + '"的数据项?').then(function () {
    DelTenant({ id: row.id }).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(function () {
    return changeRoleStatus(row.roleId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleDataScope":
      handleDataScope(row);
      break;
    case "handleAuthUser":
      handleAuthUser(row);
      break;
    default:
      break;
  }
}

/** 分配用户 */
function handleAuthUser(row) {
  router.push("/system/role-auth/user/" + row.roleId);
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    menuOptions.value = response.data;
  });
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys();
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    tenantName: null,
    tenantDoMain: null,
    tenantDes: null,
    tenantOrders: 0,
    id: null
  };
  proxy.resetForm("roleRef");
}

/** 总览跳转 */
function handleTonav(row) {
  let { id, entId, showType } = row;
  if (showType === 1) {
    router.push(`/public/cloudTv/dataView?id=${id}&entId=${entId}`)
  }else if (showType === 3) {
    router.push(`/public/cloudTv/e800tDataView?id=${id}&entId=${entId}`)
  }
}


/** 添加 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加系统";
}

/** 修改 */
// 在 handleUpdate 方法中
function handleUpdate(row) {
  mapPickerDialogRef.value.openDialog();
  // reset();
  // // 填充表单数据
  // Object.keys(form.value).forEach(key => {
  //   form.value[key] = row[key];
  //   if (form.value[key] == undefined) {
  //     form.value[key] = null
  //   }
  // });
  // open.value = true;
  // title.value = "修改系统";
}

// 打开地图选点
function openMapPicker() {
  if (mapPickerDialogRef.value) {
    // 如果有经纬度，解析并传入
    let position = null;
    if (form.value.lngLat) {
      const [lng, lat] = form.value.lngLat.split(',');
      if (lng && lat) {
        position = { lng: parseFloat(lng), lat: parseFloat(lat) };
      }
    }
    mapPickerDialogRef.value.openDialog(position);
  }
}

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then(response => {
    menuOptions.value = response.menus;
    return response;
  });
}

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then(response => {
    deptOptions.value = response.depts;
    return response;
  });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "dept") {
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else if (type == "dept") {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    form.value.deptCheckStrictly = value ? true : false;
  }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

// 处理值变化的方法
const handleChange = (value) => {
  if (Number.isInteger(value)) {
    if (value < 0) {
      form.value.tenantOrders = 0;
    } else if (value > 9) {
      form.value.tenantOrders = 9;
    }
  } else {
    // 如果不是整数，恢复到上一个有效值
    form.value.tenantOrders = Math.round(form.value.tenantOrders);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        EditTenant({
          ...form.value,
          uniqueKey: userInfo.info.uniqueKey
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        AddTenant(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
  if (value !== "2") {
    deptRef.value.setCheckedKeys([]);
  }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openDataScope.value = false;
      getList();
    });
  }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}
getList();
</script>
